package com.zzyl.nursing.service.impl;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住办理Service业务层处理
 * 
 * @author cyj
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住办理
     * 
     * @param id 入住办理主键
     * @return 入住办理
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住办理列表
     * 
     * @param checkIn 入住办理
     * @return 入住办理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住办理
     * 
     * @param checkIn 入住办理
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住办理
     * 
     * @param checkIn 入住办理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住办理
     * 
     * @param ids 需要删除的入住办理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住办理信息
     * 
     * @param id 入住办理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    //申请入住
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo()));
        if (!ObjectUtils.isEmpty(elder) && elder.getStatus().intValue()!=0 && elder.getStatus().intValue() != 5){
            throw new BaseException("老人已经入住");
        }

        Integer count = bedMapper.updateBedStatus(dto.getCheckInConfigDto().getBedId());
        if (count == 0){
            throw new BaseException("占用床位失败");
        }
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        if (elder != null){//修改
            elderMapper.updateById(elder);
        }else {
            elder = new Elder();
            elder.setCreateTime(new Date());
            BeanUtils.copyProperties(dto.getCheckInElderDto(),elder);
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elder.setCreateTime(new Date());
            //新增
            elderMapper.insert(elder);
        }

        //4、新增签约办理
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber()); //合同编号
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());  //开始时间
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());   //结束时间
        contract.setStatus(contract.getStartDate().isAfter(LocalDateTime.now())? 1 :0); //状态
        contract.setCreateTime(new Date());
        contractMapper.insert(contract);

        //5、新增入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        //家属信息->remark
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkIn.setCreateTime(new Date());
        checkInMapper.insert(checkIn);

        //6、新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setCreateTime(new Date());
        checkInConfigMapper.insert(checkInConfig);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //老人响应信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo=new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        vo.setCheckInElderVo(checkInElderVo);
        //家属响应信息

        String remark=checkIn.getRemark();
        if(!ObjectUtils.isNull(remark)){
            vo.setElderFamilyVoList(JSONUtil.toList(remark, ElderFamilyVo.class));
        }



        //入住配置响应
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        vo.setCheckInConfigVo(checkInConfigVo);
        //签约办理响应信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .eq(Contract::getStatus, 1)
                .orderByDesc(Contract::getCreateTime)
                .last("limit 1"));
        vo.setContract(contract);
        vo.getCheckInConfigVo().setStartDate(checkIn.getStartDate());
        vo.getCheckInConfigVo().setEndDate(checkIn.getEndDate());
        vo.getCheckInConfigVo().setBedNumber(checkIn.getBedNumber());

        return vo;
    }
}
